import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { Request, Response } from 'express';

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    // 新增详细异常打印
    console.error('全局异常:', exception);

    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();

    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;

    const message =
      exception instanceof HttpException ? exception.getResponse() : exception;

    // 提取更详细的错误信息
    let errorDetail: any = {};
    if (exception instanceof Error) {
      errorDetail = {
        name: exception.name,
        stack: exception.stack,
        message: exception.message,
      };
    } else if (typeof exception === 'object' && exception !== null) {
      errorDetail = exception;
    } else {
      errorDetail = { error: exception };
    }

    response.status(status).json({
      statusCode: status,
      message,
      path: request.url,
      timestamp: new Date().toISOString(),
      error: errorDetail,
    });
  }
}
